package cn.darkhorse.jpush.service.impl;

import cn.darkhorse.common.util.HttpClentUtils;
import cn.darkhorse.jpush.service.UniPushService;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson2.JSONObject;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class UniPushServiceImpl implements UniPushService {
    //@Resource(name = "myApiHelper")
    private ApiHelper myApiHelper;
    /**
     * uniAPP推送 单推
     *
     * @param registrationId
     * @param content
     * @param title
     * @param extras
     * @return
     */
    @Override
    public String sendMsg(String registrationId, String content, String title, Map<String, String> extras,String url) {
        if(StringUtils.isBlank(registrationId)){
            log.info("无有效推送id");
            return null;
        }
        log.info("单推"+title+"通知开始！");
        JSONObject data=new JSONObject();
        data.put("push_clientid",registrationId);
        data.put("title",title);
        data.put("content",content);
        data.put("payload",extras);
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        apiConfiguration.setDomain(url);
        String result="";
        try {
             result = HttpClentUtils.httpsPost(url, data.toJSONString());
            log.info("接口通信成功！");
        } catch (Exception e) {
            log.info("错误！",e);
            throw new ServiceException(e.toString());
        }
        log.info("单推"+title+"通知结束！");
        return result;
    }
    /**
     * uniAPP推送 群推
     *
     * @param registrationIds
     * @param content
     * @param title
     * @param extras
     * @return
     */
    @Override
    public String sendMsg(List<String> registrationIds, String content, String title, Map<String, String> extras, String url) {
        if(registrationIds.size()==0){
            log.info("无有效推送id");
            return null;
        }
        log.info("群推"+title+"通知开始！");
        JSONObject data=new JSONObject();
        data.put("push_clientid",registrationIds);
        data.put("title",title);
        data.put("content",content);
        data.put("payload",extras);
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        apiConfiguration.setDomain(url);
        String result="";
        try {
            System.out.println(data.toJSONString());
            result = HttpClentUtils.httpsPost(url, data.toJSONString());
             log.info("接口通信成功！");
        } catch (Exception e) {
            log.info("错误！",e);
            throw new ServiceException(e.toString());
        }
        log.info("群推"+title+"通知结束！");
        return result;
    }
    public ApiResult<Map<String, Map<String, String>>> pushToSingleByCid(String cid, String title, String content, String linkUrl, String type) {
        PushDTO<Audience> pushDTO = this.buildPushDTO(title, content, linkUrl, type);
        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid(cid); // cid
        // 进行cid单推
        PushApi pushApi = myApiHelper.creatApi(PushApi.class);

        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success
            log.info("推送成功");
            System.out.println(apiResult.getData());
        } else {
            // failed
            log.error("推送失败");
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
        return apiResult;
    }

    /**
     * 消息参数模板
     */
    private PushDTO<Audience> buildPushDTO(String title, String content, String linkUrl, String type) {
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        //requestid需要每次变化唯一
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        pushDTO.setGroupName("wxb-group");

        // 消息通知
        GTNotification notification = new GTNotification();
        notification.setTitle(title);
        notification.setBody(content);
        //android8.0以上
        //0：无声音，无振动，不显示；
        //1：无声音，无振动，锁屏不显示，通知栏中被折叠显示，导航栏无logo;
        //2：无声音，无振动，锁屏和通知栏中都显示，通知不唤醒屏幕;
        //3：有声音，无振动，锁屏和通知栏中都显示，通知唤醒屏幕;
        //4：有声音，有振动，亮屏下通知悬浮展示，锁屏通知以默认形式展示且唤醒屏幕;
        // notification.setChannelLevel("3");

        //notification.setClickType("payload");
        //notification.setPayload(payload);
        //notification.setBadgeAddNum("1");
        /* 设置个推通道参数，更多参数请查看文档或对象源码 */

        //配置推送条件
        // 1: 表示该消息在用户在线时推送个推通道，用户离线时推送厂商通道;
        // 2: 表示该消息只通过厂商通道策略下发，不考虑用户是否在线;
        // 3: 表示该消息只通过个推通道下发，不考虑用户是否在线；
        // 4: 表示该消息优先从厂商通道下发，若消息内容在厂商通道代发失败后会从个推通道下发。
        /*Strategy strategy = new Strategy();
        strategy.setDef(1);
        strategy.setSt(1);
        Settings settings = new Settings();
        settings.setStrategy(strategy);
        pushDTO.setSettings(settings);
        //消息有效期，走厂商消息需要设置该值
        settings.setTtl(3600000);*/

        PushChannel pushChannel = new PushChannel();

        Map<String, String> map = new HashMap<>();
        map.put("title", title);
        map.put("content", content);
        // 转json对象
        String payload = JSONUtils.toJSONString(map);

        // ========================= ios离线配置 ==============================
       /* //推送苹果离线通知标题内容
        Alert alert = new Alert();
        //苹果离线通知栏标题
        alert.setTitle(title);
        //苹果离线通知栏内容
        alert.setBody(content);
        Aps aps = new Aps();
        //1表示静默推送(无通知栏消息)，静默推送时不需要填写其他参数。
        // 苹果建议1小时最多推送3条静默消息
        aps.setContentAvailable(0);
        aps.setSound("default");
        aps.setAlert(alert);
        IosDTO iosDTO = new IosDTO();
        iosDTO.setPayload(payload);
        iosDTO.setAps(aps);
        iosDTO.setType("notify");
        pushChannel.setIos(iosDTO);*/

        // =================== 安卓离线厂商通道推送消息体 ===========================
        /*AndroidDTO androidDTO = new AndroidDTO();
        pushDTO.setPushChannel(pushChannel);
        pushChannel.setAndroid(androidDTO);
        Ups ups = new Ups();
        androidDTO.setUps(ups);*/
        //各厂商自有功能单项设置
//        ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
//        ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
//        ups.addOption("HW", "/message/android/notification/importance", "HIGH");
//        ups.addOption("VV","classification",1);

        //设置options 方式一
//        ups.addOption("HW","badgeAddNum",3);
//        ups.addOption("HW","badgeClass","com.getui.demo.GetuiSdkDemoActivity");
//        ups.addOption("OP","app_message_id",11);
//        ups.addOption("VV","message_sort",1);
//        ups.addOptionAll("channel","default");

        // PushMessage在线走个推通道才会起作用的消息体
        PushMessage pushMessage = new PushMessage();
        pushMessage.setNotification(notification);
        pushDTO.setPushMessage(pushMessage);
        Map<String, Object> mapTC = new HashMap<>();
        mapTC.put("title", title);
        mapTC.put("content", content);
        mapTC.put("payload", map);
        String jsonTC = JSONUtils.toJSONString(mapTC);
        pushMessage.setTransmission(jsonTC);
        log.info("pushDTO:{}", pushDTO);
        return pushDTO;
    }

    public static void main(String[] args) {
        UniPushServiceImpl imp=new UniPushServiceImpl();
        String title="123";
        String content="123123";
        Map<String, String> extras =new HashMap<>();
        extras.put("1","123");
        extras.put("2","123");
        extras.put("3","123");
        extras.put("4","123");
        extras.put("5","123");
        String url="https://fc-mp-27f2dea0-a803-4efe-b7db-718462d5f993.next.bspapp.com/unipush";
        List<String > id=new ArrayList<>();
        id.add("123");
        id.add("456");
        id.add("789");
        id.add("123");
        String s = imp.sendMsg(id, title, content, extras,url);
        System.out.println("result"+s);
    }
}
